package com.vrv.vap.baseline.controller;

import com.vrv.vap.baseline.service.impl.AssetSystemAttributeSettingsExportService;
import com.vrv.vap.baseline.service.impl.AssetSystemAttributeSettingsImportService;
import com.vrv.vap.baseline.util.FileOperationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/api/asset_system_attribute_settings")
public class AssetSystemAttributeSettingsController {
    @Autowired
    private AssetSystemAttributeSettingsExportService assetSystemAttributeSettingsExportService;
    
    @Autowired
    private FileOperationUtil fileOperationUtil;
    
    @Autowired
    private AssetSystemAttributeSettingsImportService assetSystemAttributeSettingsImportService;
    
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        String zipFilePath = assetSystemAttributeSettingsExportService.exportZip();
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=asset_system_attribute_settings.zip");
        try {
            fileOperationUtil.writeFileToResponse(zipFilePath, response);
        } catch (IOException e) {
            throw new RuntimeException("Failed to download zip file", e);
        }
    }
    
    @PostMapping("/import")
    public ResponseEntity<String> importData(@RequestParam("file") MultipartFile file) {
        try {
            // 验证文件类型
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body("请选择要上传的文件");
            }
            
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !originalFilename.endsWith(".zip")) {
                return ResponseEntity.badRequest().body("只支持上传ZIP格式的文件");
            }
            
            // 调用导入服务处理ZIP文件
            int importedCount = assetSystemAttributeSettingsImportService.importFromZip(file);
            
            return ResponseEntity.ok("成功导入" + importedCount + "条记录");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("导入失败: " + e.getMessage());
        }
    }
}